//
//  NewPageViewController.m
//  SuperNews
//
//  Created by qiang on 16/1/9.
//  Copyright © 2016年 qiang. All rights reserved.
//

#import "NewPageViewController.h"
#import "YZQCollectionViewCell.h"
#import "YZQWebViewViewController.h"
#import "YZQPhotosViewController.h"
#import "YZQ24HourViewController.h"

@interface NewPageViewController () <UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, NewsCollectionViewCellDelegate>
@property (nonatomic, strong) UIScrollView *scrollV;
@property (nonatomic, strong) UICollectionView *collectV;
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, retain) UIView *titleV;
@property (nonatomic, strong) NSMutableArray *newsArr;
@property (nonatomic, assign) NSInteger buttonNum;
@property (nonatomic, assign) NSMutableArray *jsonArray;

@property (nonatomic, strong) YZQCollectionViewCell *newsCollectionViewCell;

@end

@implementation NewPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"top_navi_bell_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction:)];
    [self createSubviews];
    [self getData];
    
    self.titleArr = [NSMutableArray array];
    self.imageArr = [NSMutableArray array];
    self.newsArr = [NSMutableArray array];
    self.jsonArray = [NSMutableArray array];
}

- (void)createSubviews
{
    [self createTitleScrollView];
    // 轮播图;
    [self createCollectionView];
}

- (void)createTitleScrollView
{
    // 标题数组
    NSArray *array = [NSArray arrayWithObjects:@"头条", @"娱乐", @"热点", @"体育", @"订阅", @"财经", @"科技", @"汽车", nil];
    
    // 滑动条初始化
    self.scrollV = [[UIScrollView alloc]init];
    
    [self.view addSubview:self.scrollV];
    
    [self.scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.equalTo(self.view);
        make.width.equalTo(self.view).offset(-35);
        make.height.mas_equalTo(40);
        
    }];
    self.scrollV.showsHorizontalScrollIndicator = NO;
    self.scrollV.showsVerticalScrollIndicator = NO;
    self.scrollV.bounces = NO;
    self.scrollV.contentSize = CGSizeMake(YZQTITLEBUTTONWIDTH * 8, 0);
    self.scrollV.delegate = self;
    for (NSInteger i = 0; i < array.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 3000 + i;
        if (0 == i) {
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:20];
        } else {
            button.titleLabel.font = [UIFont systemFontOfSize:15];
        }
        [self.scrollV addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(YZQTITLEBUTTONWIDTH * i);
            make.top.mas_equalTo(self.view);
            make.width.mas_equalTo(YZQTITLEBUTTONWIDTH);
            make.height.mas_equalTo(YZQTITLEHIEGHT);
            
        }];
    }
}
- (void)createCollectionView
{
    // collectionView子方法
    UICollectionViewFlowLayout *flowL = [[UICollectionViewFlowLayout alloc] init] ;
    
    // 滚动方向
    flowL.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowL.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 49 - YZQTITLEHIEGHT - 64);
    // 左右间距为0
    flowL.minimumLineSpacing = 0;
    
    self.collectV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.scrollV.frame.origin.y + self.scrollV.frame.size.height + 40, self.view.frame.size.width, self.view.frame.size.height - self.scrollV.frame.size.height - 64 - 49) collectionViewLayout:flowL];
    
    [self.view addSubview:self.collectV];
    [self.collectV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.scrollV.mas_bottom);
        
    }];
    // tag值
    self.collectV.tag = 2001;
    // 允许滑动
    self.collectV.pagingEnabled = YES;
    // 背景颜色
    self.collectV.backgroundColor = [UIColor whiteColor];
    // 隐藏滚动条
    self.collectV.showsHorizontalScrollIndicator = NO;
    self.collectV.showsVerticalScrollIndicator = NO;
    // 不允许边界反弹
    self.collectV.bounces = NO;
    // 代理
    self.collectV.delegate = self;
    self.collectV.dataSource = self;
    
    // 注册cell
    [self.collectV registerClass:[YZQCollectionViewCell class] forCellWithReuseIdentifier:@"newsCollectionViewCell"];
    [self.view addSubview:self.collectV];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 在减速结束的方法里判断偏移量
    if (scrollView == self.collectV) {
        
        // 获取当前页数
        NSInteger page = self.collectV.contentOffset.x / self.collectV.frame.size.width;
        
        // 滑动到相应的Button颜色变红
        for (NSInteger i = 0; i < 8; i++) {
            
            // 如果不是当前页面,设为初始颜色
            if (i != page) {
                UIButton *button = [self.scrollV.subviews objectAtIndex:i];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:15];
                
                // 如果是当前页面,设置红色放大
            } else {
                UIButton *button = [self.scrollV.subviews objectAtIndex:i];
                [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:20];
            }
        }
        // 计算偏移量
        CGPoint point = CGPointMake(page * YZQTITLEBUTTONWIDTH - (self.scrollV.frame.size.width - YZQTITLEBUTTONWIDTH) / 2.0 - 35.0, 0);
        // 判断
        if (point.x < 0) {
            point.x = 0;
        } else if (point.x + self.scrollV.frame.size.width > self.scrollV.contentSize.width) {
            point.x = self.scrollV.contentSize.width - self.scrollV.frame.size.width;
        }
        // 偏移
        [self.scrollV setContentOffset:point animated:YES];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.newsArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.newsCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"newsCollectionViewCell" forIndexPath:indexPath];
    
    
    self.newsCollectionViewCell.newsCollectionViewCelldelegate = self;
    self.newsCollectionViewCell.pageCountArr = self.newsArr;
    
    self.newsCollectionViewCell.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh)];
    
    //下拉刷新
    self.newsCollectionViewCell.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewHeaderRefresh)];
    

    
    for (NSDictionary *dic in self.newsArr) {
        NSString *type = [dic objectForKey:@"type"];
        if ([type isEqualToString:[NSString stringWithFormat:@"%ld", indexPath.row]]) {
            NSMutableArray *smallArray = dic[@"array"];
            self.newsCollectionViewCell.tableViewArr = smallArray;
            [self.newsCollectionViewCell.tableV reloadData];
        }
    }
    
    return self.newsCollectionViewCell;
}
- (void)tableViewRefresh
{
    // 先获取json文件
    NSString *hpJsonPath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
    
    // 这个json文件存放的是字符串, 转成data
    NSData *data = [NSData dataWithContentsOfFile:hpJsonPath];
    
    // 格式化成NSArray
    self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    // 获取当前页数
    NSInteger item = self.collectV.contentOffset.x / self.collectV.frame.size.width;
    // 获取区数 只有一个区
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
    // 取出数据
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[self.jsonArray objectAtIndex:indexPath.item]];
   
    // 获取cell
    YZQCollectionViewCell *cell = (YZQCollectionViewCell *)[self.collectV cellForItemAtIndexPath:indexPath];
    
    // cell页数＋1
    cell.pageCount++;
    
    // 获取字符串
    NSString *string = [dic valueForKey:@"URL"];
    
    // 拼接字符串
    NSRange range = [string rangeOfString:@"0-20.html"];
    NSString *finalStr = [string stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%ld-20.html", cell.pageCount * 20]];
    NSLog(@"sssssssssssss");
    // 刷新响应的数据
    [self refreshDataFromNet:finalStr key:dic[@"dicKey"] type:dic[@"type"]];
    
}

#pragma mark- 刷新响应的数据
- (void)refreshDataFromNet:(NSString *)url key:(NSString *)key type:(NSString *)type
{
    
    [AFNetTool getNetWithURL:url body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
    
        NSDictionary *dataDic = (NSDictionary *)responseObject;
        
        NSArray *tArray = [dataDic objectForKey:key];
        
        for (NSDictionary *dic in self.newsArr) {
            
            if ([dic[@"type"] isEqualToString:type]) {
                
                NSMutableArray *arrM = [dic valueForKey:@"array"];
                
                for (NSMutableDictionary *dic in tArray) {
                    NewsPageModel *newsM = [NewsPageModel baseModelWithDic:dic];
                    [arrM addObject:newsM];
                }
            }
        }
        [self.collectV reloadData];

        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
    }];
    
}


- (void)tableViewHeaderRefresh
{
    [self getData];
    [self.newsCollectionViewCell.tableV.mj_header endRefreshing];
}


- (void)getData
{
    // 先获取json文件
    NSString *hpJsonPath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
    
    // 这个json文件存放的是字符串, 转成data
    NSData *data = [NSData dataWithContentsOfFile:hpJsonPath];
    
    // 格式化成NSArray
    self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    // 遍历数组, 拿到参数去网络请求
    for (NSDictionary *dic in self.jsonArray) {
        // 取所有的数据
        [self getDataWithNetUrl:dic[@"URL"] key:dic[@"dicKey"] type:dic[@"type"]];
    }
    
}
- (void)getDataWithNetUrl:(NSString *)Url key:(NSString *)key type:(NSString *)type
{
    [AFNetTool getNetWithURL:Url body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSMutableArray *arrM = [NSMutableArray array];
        
        for (NSMutableDictionary *dic in responseObject[key]) {
            NewsPageModel *newsM = [[NewsPageModel alloc] initWithDic:dic];
            [arrM addObject:newsM];
            
        }
        // 存放对应类型的小数组内容
        NSDictionary *dic = @{@"type":type, @"array":arrM};
        [self.newsArr addObject:dic];
        [self.collectV reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
    }];
    
}

- (void)leftBarButtonAction:(id)sender
{
    YZQ24HourViewController *hourVC = [[YZQ24HourViewController alloc] init];
    UINavigationController *hourNC = [[UINavigationController alloc] initWithRootViewController:hourVC];
    [hourNC.navigationBar setBackgroundImage:[UIImage imageNamed:@"todaynews_header_bg_day"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    
    [self presentViewController:hourNC animated:YES completion:^{
        
        
        
    }];
    
}
- (void)buttonAction:(UIButton *)sender
{
    // 获取当前按钮数
    self.buttonNum = sender.tag - 3000;
    
    // collectV偏移
    CGFloat collectRet = (sender.tag - 3000) * self.view.frame.size.width;
    self.collectV.contentOffset = CGPointMake(collectRet, 0);
    
    
    // 点击Button颜色变黑
    for (NSInteger i = 0 ; i < 8; i++) {
        // 判断是否与相应按钮相等 改变颜色
        if (i != sender.tag - 3000) {
            UIButton *button = [self.scrollV.subviews objectAtIndex:i];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
        } else {
            UIButton *button = [self.scrollV.subviews objectAtIndex:i];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:20];
        }
    }

}
- (void)didSelectWithItem:(NewsPageModel *)item type:(NSString *)type
{
    if ([type isEqualToString:@"normal"] || [type isEqualToString:@"big"]) {
        
        YZQWebViewViewController *web = [[YZQWebViewViewController alloc]init];
//        web.url = item.url_3w;
        web.docId = item.docid;
        [self.navigationController pushViewController:web animated:YES];
        
    }
    if ([type isEqualToString:@"photos"]) {
        
        YZQPhotosViewController *photos = [[YZQPhotosViewController alloc]init];
        photos.photosetID = item.photosetID;
        photos.photoTitle = item.title;
        [self.navigationController pushViewController:photos animated:YES];
        
    }
    
}

- (void)sendMessage:(NSString *)message arr:(NSMutableArray *)arr
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
